package com.qs.utils;

/**
 * ClassName: LockUtils
 * Package: com.qs.utils
 * Description:
 *
 * @Author: @weixueshi
 * @Create: 2023/12/5 - 13:05
 * @Version: v1.0
 */

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.IdUtil;
import com.qs.constant.RedisConstant;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 获取锁和释放锁工具
 */
@Component
public class LockUtils {
    private static RedisTemplate redisTemplate;

    public LockUtils(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取锁方法
     * @param key
     */
    public static boolean tryLock(String key,String value){
        //获取锁，要对锁设置一个过期时间，防止某些异常导致死锁
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, value, RedisConstant.CACHE_LOCK_EXPIRE, TimeUnit.SECONDS);
        //如果为true则说明获取到了锁，若返回false则说明前面已经有线程获取到了锁
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     * @param key
     */
    public static void unLock(String key){
        //直接删除锁的键即可
        redisTemplate.delete(key);
    }
}
